<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="文章标题">
          <el-input v-model="searchForm.title" placeholder="请输入文章标题" clearable />
        </el-form-item>
        <el-form-item label="文章分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" :icon="Plus" @click="handleAdd">添加文章</el-button>
      <el-button type="danger" :icon="Delete" :disabled="!selectedItems.length" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="文章标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.category }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="views" label="阅读量" width="100" sortable />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '已发布' ? 'success' : scope.row.status === '草稿' ? 'info' : 'warning'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable />
        <el-table-column prop="updateTime" label="更新时间" width="180" sortable />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.status !== '已发布'" link type="success" size="small" @click="handlePublish(scope.row)">发布</el-button>
            <el-button v-if="scope.row.status === '已发布'" link type="warning" size="small" @click="handleUnpublish(scope.row)">下架</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加文章' : '编辑文章'"
      width="850px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="formData.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <el-upload
            class="cover-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleCoverChange"
          >
            <img v-if="formData.coverImage" :src="formData.coverImage" class="cover" />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：800 x 400 像素，格式：JPG/PNG</div>
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input v-model="formData.summary" type="textarea" rows="3" placeholder="请输入文章摘要" />
        </el-form-item>
        <el-form-item label="内容" prop="content" class="content-editor">
          <div class="editor-container">
            <el-input v-model="formData.content" type="textarea" rows="15" placeholder="请输入文章内容" />
            <!-- 在实际项目中，可以使用富文本编辑器如 tinymce 或 wangeditor -->
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="已发布">发布</el-radio>
            <el-radio label="草稿">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否置顶" prop="isTop">
          <el-switch v-model="formData.isTop" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文章详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="文章详情"
      width="800px"
    >
      <div class="article-detail">
        <h1 class="article-title">{{ detailData.title }}</h1>
        <div class="article-meta">
          <span>作者：{{ detailData.author }}</span>
          <span>分类：{{ detailData.category }}</span>
          <span>阅读量：{{ detailData.views }}</span>
          <span>发布时间：{{ detailData.updateTime }}</span>
        </div>
        <div v-if="detailData.coverImage" class="article-cover">
          <img :src="detailData.coverImage" alt="封面图片" />
        </div>
        <div class="article-summary">
          <strong>摘要：</strong>{{ detailData.summary }}
        </div>
        <div class="article-content" v-html="detailData.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getHealthKnowledgeList, getHealthKnowledgeDetail, addHealthKnowledge, updateHealthKnowledge, deleteHealthKnowledge, batchDeleteHealthKnowledge } from '@/api/knowledge'

// 数据加载状态
const loading = ref(false)

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedItems = ref([])

// 搜索表单
const searchForm = reactive({
  title: '',
  category: '',
  status: ''
})

// 文章分类选项
const categoryOptions = [
  { value: '中医养生', label: '中医养生' },
  { value: '健康饮食', label: '健康饮食' },
  { value: '运动健身', label: '运动健身' },
  { value: '心理健康', label: '心理健康' },
  { value: '常见疾病', label: '常见疾病' },
  { value: '中药百科', label: '中药百科' },
  { value: '养生方剂', label: '养生方剂' },
  { value: '针灸推拿', label: '针灸推拿' }
]

// 状态选项
const statusOptions = [
  { value: '已发布', label: '已发布' },
  { value: '草稿', label: '草稿' },
  { value: '已下架', label: '已下架' }
]

// 表单数据
const dialogType = ref('add') // 'add' 或 'edit'
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const formRef = ref(null)
const formData = reactive({
  id: '',
  title: '',
  category: '',
  author: '',
  coverImage: '',
  summary: '',
  content: '',
  status: '草稿',
  isTop: false,
  views: 0
})
const detailData = ref({})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入文章摘要', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

// 搜索操作
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  searchForm.category = ''
  searchForm.status = ''
  handleSearch()
}

// 获取文章列表
const fetchData = () => {
  loading.value = true
  // 实际应用中应该调用API
  // const params = {
  //   ...searchForm,
  //   page: currentPage.value,
  //   size: pageSize.value
  // }
  // getHealthKnowledgeList(params).then(res => {
  //   tableData.value = res.data.list
  //   total.value = res.data.total
  //   loading.value = false
  // }).catch(() => {
  //   loading.value = false
  // })

  // 模拟数据
  setTimeout(() => {
    const mockData = Array.from({ length: 20 }).map((_, index) => {
      const status = ['已发布', '草稿', '已下架'][index % 3]
      return {
        id: index + 1,
        title: `健康养生文章${index + 1}：${['中医调理', '饮食建议', '运动指南', '防病攻略'][index % 4]}`,
        category: categoryOptions[index % categoryOptions.length].value,
        author: `作者${index + 1}`,
        coverImage: `https://via.placeholder.com/800x400?text=Health+Article+${index + 1}`,
        summary: `这是一篇关于${categoryOptions[index % categoryOptions.length].value}的文章摘要，介绍了相关的养生知识和实用技巧。`,
        content: `<p>这是文章的正文内容，详细介绍了${categoryOptions[index % categoryOptions.length].value}的相关知识。</p><p>包括理论基础、实践方法以及注意事项等内容。</p><p>希望读者通过阅读本文能够获得有用的健康知识，并在生活中加以实践。</p>`,
        status: status,
        isTop: index < 3,
        views: Math.floor(Math.random() * 1000) + 100,
        createTime: '2023-05-20 10:30:00',
        updateTime: '2023-05-21 15:45:00'
      }
    })
    
    tableData.value = mockData
    total.value = 100
    loading.value = false
  }, 500)
}

// 选择变更
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

// 查看文章
const handleView = (row) => {
  // 实际应用中应该调用API
  // getHealthKnowledgeDetail(row.id).then(res => {
  //   detailData.value = res.data
  //   viewDialogVisible.value = true
  // })

  // 模拟数据
  detailData.value = { ...row }
  viewDialogVisible.value = true
}

// 添加文章
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑文章
const handleEdit = (row) => {
  dialogType.value = 'edit'
  resetForm()
  
  // 复制数据，避免双向绑定
  Object.keys(formData).forEach(key => {
    formData[key] = row[key]
  })
  
  dialogVisible.value = true
}

// 删除文章
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该文章吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 实际应用中应该调用API
    // await deleteHealthKnowledge(row.id)
    
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    
    // 重新加载数据
    fetchData()
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择要删除的文章')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedItems.value.length} 篇文章吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 实际应用中应该调用API
    // const ids = selectedItems.value.map(item => item.id)
    // await batchDeleteHealthKnowledge(ids)
    
    ElMessage({
      type: 'success',
      message: '批量删除成功'
    })
    
    // 重新加载数据
    fetchData()
  }).catch(() => {})
}

// 发布文章
const handlePublish = (row) => {
  ElMessageBox.confirm('确定要发布该文章吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    // 实际应用中应该调用API
    // await updateHealthKnowledge(row.id, { ...row, status: '已发布' })
    
    ElMessage({
      type: 'success',
      message: '发布成功'
    })
    
    // 更新本地数据
    row.status = '已发布'
  }).catch(() => {})
}

// 下架文章
const handleUnpublish = (row) => {
  ElMessageBox.confirm('确定要下架该文章吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 实际应用中应该调用API
    // await updateHealthKnowledge(row.id, { ...row, status: '已下架' })
    
    ElMessage({
      type: 'success',
      message: '下架成功'
    })
    
    // 更新本地数据
    row.status = '已下架'
  }).catch(() => {})
}

// 封面图片变更
const handleCoverChange = (file) => {
  formData.coverImage = URL.createObjectURL(file.raw)
}

// 关闭对话框前的确认
const handleDialogClose = (done) => {
  if (formRef.value.isModified) {
    ElMessageBox.confirm('有未保存的更改，确定要关闭吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      done()
    }).catch(() => {})
  } else {
    done()
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 实际应用中应该调用API
      // if (dialogType.value === 'add') {
      //   await addHealthKnowledge(formData)
      // } else {
      //   await updateHealthKnowledge(formData.id, formData)
      // }
      
      ElMessage({
        type: 'success',
        message: dialogType.value === 'add' ? '添加成功' : '更新成功'
      })
      
      dialogVisible.value = false
      fetchData()
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  Object.keys(formData).forEach(key => {
    if (key === 'status') {
      formData[key] = '草稿'
    } else if (key === 'isTop') {
      formData[key] = false
    } else if (key === 'views') {
      formData[key] = 0
    } else {
      formData[key] = ''
    }
  })
}

// 分页大小变更
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 页码变更
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .action-container {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-start;
    gap: 10px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .content-editor {
    .editor-container {
      border: 1px solid #dcdfe6;
      border-radius: 4px;
    }
  }
  
  .cover-uploader {
    .cover {
      width: 300px;
      height: 150px;
      object-fit: cover;
      border-radius: 4px;
    }
    
    .cover-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 300px;
      height: 150px;
      line-height: 150px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 4px;
    }
    
    .upload-tip {
      font-size: 12px;
      color: #606266;
      margin-top: 5px;
    }
  }
  
  .article-detail {
    .article-title {
      font-size: 24px;
      text-align: center;
      margin-bottom: 20px;
    }
    
    .article-meta {
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
      gap: 20px;
      margin-bottom: 20px;
      font-size: 14px;
      color: #606266;
    }
    
    .article-cover {
      margin-bottom: 20px;
      text-align: center;
      
      img {
        max-width: 100%;
        border-radius: 4px;
      }
    }
    
    .article-summary {
      background-color: #f5f7fa;
      padding: 15px;
      border-radius: 4px;
      margin-bottom: 20px;
      font-size: 14px;
      line-height: 1.6;
    }
    
    .article-content {
      font-size: 16px;
      line-height: 1.8;
      
      p {
        margin-bottom: 15px;
      }
    }
  }
}
</style> 